<template>
  <div class="detailpage">
    <div class="back">
      <BackNav left-text="返回" left-arrow title="商品详情"></BackNav>
    </div>
    <div>
      <div class="detail-img">
        <img :src="productlist.large_img" class="auto-img" alt="">
      </div>
      <div class="detail-box">
        <div class="pro-info">
          <div>
            <div class="zh-name">{{ productlist.name }}</div>
            <div class="en-name">{{ productlist.enname }}</div>
          </div>
          <div class="pro-price">&yen;{{ productlist.price }}</div>
        </div>
        <!-- 规格 -->
        <div class="pro-rule">
          <div
            class="pro-rule-item"
            v-for="(item, index) in productlist.rules"
            :key="index"
          >
            <div class="pro-rule-title">{{ item.title }}</div>
            <div class="pro-sub-rule">
              <div
                ref="a"
                @click="toggle(item, v)"
                :class="[
                  'pro-sub-rule-item',
                  { active: item.activeIndex == v },
                ]"
                v-for="(i, v) in item.rule"
                :key="v"
              >
                {{ i.title }}
              </div>
            </div>
          </div>
        </div>

        <!-- 选择数量 -->
        <div class="select-count">
          <div class="select-text">选择数量</div>
          <div class="select-box">
            <van-stepper
              v-model="value"
              theme="round"
              button-size="22"
              disable-input
            />
          </div>
        </div>

        <!-- 描述 -->
        <div class="decribe">
          <div class="decribe-title">商品描述</div>
          <div class="decribe-text">
            <div
              class="decribe-text-item"
              v-for="(item, index) in productlist.desc"
              :key="index"
            >
              {{ index + 1 }}.{{ item }}
            </div>
          </div>
        </div>

        <!-- 商品导航 -->
        <div>
          <van-goods-action>
            <van-goods-action-icon
              icon="bag"
              @click="gouwu"
              text="购物袋"
              color="#646566"
              :badge="showcount == 0 ? '' : showcount"
            />
            <van-goods-action-icon
              icon="like"
              :text="islike ? '已收藏' : '未收藏'"
              :color="islike ? '#0c34ba' : '#646566'"
              @click="like"
            />
            <van-goods-action-button
              color="#2450F2"
              type="warning"
              text="加入购物袋"
              @click="addShopbag"
            />
            <van-goods-action-button
              color="#0c34ba"
              type="danger"
              text="立即购买"
              @click="buy"
            />
          </van-goods-action>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// 导入导航组件
import BackNav from "../components/BackNav.vue";
export default {
  name: "Detail",
  created() {
    // 获取商品pid
    this.pid = this.$route.params.pid;
    this.getProductDetailByPid();
    this.findUserLike();
    this.findUserShopbagCount();
  },
  data() {
    return {
      value: "",
      islike: false,
      pid: "",
      // 记录当前的商品数据
      productlist: [],
      // 购物袋商品总数量
      showcount: 0,
      activeIndex: 0,
      // 规格
      rule: "",
    };
  },
  components: {
    BackNav,
  },
  methods: {
    // 通过pid查询商品详细信息
    getProductDetailByPid() {
      this.axios({
        method: "get",
        url: "/productDetail",
        params: {
          pid: this.pid,
        },
      })
        .then((res) => { 
          if (res.data.code == 600) {
            let data = res.data.result[0];
            // 根据\n截取商品描述
            data.desc = data.desc.split(/\n/);
            let ruleData = ["cream", "sugar", "milk", "tem"];
            let rules = [];
            // 如果有值才可以添加
            // {
            //    title:'糖',
            //    activeIndex:0,
            //    rule:[
            //       {title:'全糖'},{title:'半糖'}
            //    ]
            // }
            ruleData.forEach((v) => {
              if (!data[v]) return;
              let r = {
                title: data[`${v}_desc`],
                activeIndex: 0,
                rule: [],
              };
              //截取无糖/半分糖/全糖 格式
              let rs = data[v].split(/\//);
              rs.forEach((item) => {
                let subRule = {
                  title: item,
                };
                r.rule.push(subRule);
              });
              rules.push(r);
            });
            data.rules = rules;
            this.productlist = data;
          }
        })
        .catch((err) => {
          
        });
    },
    // 切换规格
    toggle(item, v) {
      if (item.activeIndex == v) return;
      item.activeIndex = v;
      let arr = [];
      this.$nextTick(() => {
        for (let i = 0; i < this.$refs.a.length; i++) {
          if (this.$refs.a[i].classList.contains("active")) {
            arr.push(this.$refs.a[i].innerText);
          }
        }
        arr = arr.join("/");
        this.rule = arr;
      });
    },
    // 是否收藏
    like() {
      let url = "";
      if (this.islike) {
        url = "/notlike";
      } else {
        url = "/like";
      }
      this.axios({
        method: "post",
        url,
        data: {
          pid: this.pid,
        },
      })
        .then((res) => {
          // 
          if (res.data.code == 700) {
            this.$toast(res.data.msg);
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 200);
          }
          this.$toast(res.data.msg);
          if (res.data.code === 800) {
            this.islike = true;
          } else if (res.data.code == 900 && res.data.result == 1) {
            this.islike = false;
          }
        })
        .catch((err) => {
          
        });
    },
    // 查询用户是否收藏商品
    findUserLike() {
      this.axios({
        method: "get",
        url: "/findlike",
        params: {
          pid: this.pid,
        },
      })
        .then((res) => {
          if (res.data.code == 1000 && res.data.result.length == 1) {
            this.islike = true;
          }
        })
        .catch((err) => {
          
        });
    },
    // 加入购物袋
    addShopbag() {
      // 获取商品规格
      let rules = [];
      this.productlist.rules.forEach((v) => {
        rules.push(v.rule[v.activeIndex].title);
      });
      // 
      this.axios({
        method: "post",
        url: "/addShopcart",
        data: {
          pid: this.pid,
          rule: rules.join("/"),
          count: this.value,
        },
      })
        .then((res) => {
          this.sid = res.data.sid;
          if (res.data.code == 700) {
            this.$toast(res.data.msg);
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 200);
          }
          this.$toast(res.data.msg);
          if (res.data.code == 3000) {
            this.showcount += this.value;
          }
        })
        .catch((err) => {
          
        });
    },
    // 查询用户购物袋数量
    findUserShopbagCount() {
      this.axios({
        method: "get",
        url: "/shopcartCount",
      })
        .then((res) => {
          // 
          if (res.data.code == 4000) {
            this.showcount = res.data.result;
          }
        })
        .catch((err) => {
          
        });
    },
    // 点击购物车
    gouwu() {
      this.$router.push({ name: "ShopBag" });
    },
    //立即购买
    buy() {},
  },
};
</script>
<style lang="less" scoped>
.detail-img {
  background-color: #f0f0f0;
}
.detailpage {
  padding-bottom: 50px;
  .back {
    position: sticky;
    top: 0;
  }
}
.detail-box {
  margin: 0 10px;
  padding: 10px;
  position: relative;
  top: -20px;
  background: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  .pro-info {
    display: flex;
    .zh-name {
      font-size: 14px;
    }
    .en-name {
      color: #999;
    }
    .pro-price {
      margin-left: auto;
      color: #e4393c;
      font-size: 14px;
      font-weight: bold;
    }
  }
  .pro-rule {
    margin-top: 30px;
    .pro-rule-item {
      display: flex;
      .pro-rule-title {
        width: 50px;
        height: 24px;
        line-height: 24px;
      }
      .pro-sub-rule {
        display: flex;
        .pro-sub-rule-item {
          width: 60px;
          height: 24px;
          line-height: 24px;
          text-align: center;
          background: #e8e8e8;
          margin-right: 10px;
          border-radius: 12px;
          margin-bottom: 10px;
          &:last-child {
            margin-bottom: 0;
          }
          &:last-child {
            margin-right: 0;
          }
          &.active {
            background-color: #0c34ba;
            color: white;
          }
        }
      }
    }
  }
  .select-count {
    margin-top: 20px;
    padding: 10px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    .select-text {
      font-size: 14px;
    }
    .select-box {
      margin-left: auto;
    }
  }
  .decribe {
    margin-top: 20px;
    .decribe-title {
      font-size: 14px;
    }
    .decribe-text {
      margin-top: 10px;
      .decribe-text-item {
        color: #666;
        margin-bottom: 5px;
      }
    }
  }
}
/deep/ .van-stepper--round .van-stepper__plus {
  background-color: #0c34ba;
}
/deep/ .van-stepper--round .van-stepper__minus {
  border-color: #0c34ba;
  color: #0c34ba;
}
.color {
  color: #0c34ba;
  background: #0c34ba;
}
</style>